package com.tarena.lbs.basic.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.basic.web.dao.repository.TagLibraryRepository;
import com.tarena.lbs.pojo.basic.po.TagLibraryPO;
import com.tarena.lbs.pojo.basic.vo.TagLibraryVO;
import com.tarena.lbs.pojo.basic.vo.TagVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TagService {
    @Autowired
    private TagLibraryRepository tagLibraryRepository;
    public Map<String, List<TagVO>> getTags(Integer tagType) {
        //1.查询 用户标签|文章标签 所有1,2级内容
        List<TagLibraryPO> pos = getTagsByType(tagType);
        log.info("查询到所有的文章标签:{}",pos);
        //2.封装map
        return assemblePo2Map(pos);
    }

    private Map<String, List<TagVO>> assemblePo2Map(List<TagLibraryPO> pos) {
        //1.pos没有分级 包含所有文章 标签 包括1,2级所有内容
        Map<String,List<TagVO>> mapVO = new HashMap<>();
        //2.筛选一级标签 作为mapkey值使用一级标签的名称 stream()的过滤 parentId=0 一定就是一级标签
        List<TagLibraryPO> firstLevelPos = pos.stream().filter(po -> po.getTagParentId().equals(0))
                .collect(Collectors.toList());
        log.info("拿到当前业务的 一级标签列表:{}",firstLevelPos);
        //3.循环一级标签列表 拿到标签名字做key值
        for (TagLibraryPO firstLevelPo : firstLevelPos) {
            //3.1 一级标签名字 map key有了
            String firstLevelTagName = firstLevelPo.getTagName();
            //3.2 筛选当前标签下级标签
            Integer firstLevelTagId = firstLevelPo.getId();
            List<TagLibraryPO> secondLevelPos =
                    pos.stream().filter(po -> po.getTagParentId().equals(firstLevelTagId))
                            .collect(Collectors.toList());
            log.info("拿到当前业务的 二级标签列表:{}",secondLevelPos);
            //3.3 将二级标签的pos转化成vos
            List<TagVO> secondLevelVos = secondLevelPos.stream().map(po->{
                TagVO vo = new TagVO();
                vo.setTagCategoryName(firstLevelTagName);
                TagLibraryVO tagVo = new TagLibraryVO();
                BeanUtils.copyProperties(po,tagVo);
                vo.setTagLibraryBO(tagVo);
                return vo;
            }).collect(Collectors.toList());
            log.info("拿到当前业务的 二级标签VO列表:{}",secondLevelVos);
            mapVO.put(firstLevelTagName,secondLevelVos);
        }
        return mapVO;
    }

    private List<TagLibraryPO> getTagsByType(int tagType) {
        QueryWrapper<TagLibraryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_type",tagType);
        return tagLibraryRepository.list(queryWrapper);
    }

}
